/*
SmartKinect jQuery Plugin Module

Name:	 	: Seneca BV
Country		: The Netherlands
Copyright	: Copyright (c) 2012, Seneca BV
Author	 	: Demian Buijs
Created	 	: 18-04-2012

Copyright (c) 2012, Seneca BV
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 

*/

(function( $ ){

  $.fn.smartKinect = function(options) {
  
    var defaults = {
		boxWidth:   	pageWidth(),
		boxHeight:		pageHeight(),
		wsServer:		"ws://localhost:8181",
		captureFrames:	1,
		offsetX:		0,
		offsetY:		.5,
		accelerationX:	.2,
		accelerationY:	.2,
		onePlayeronly:	true,
		elevationAngle:	6,
		cdi:			200,
		hoverTime:		4000,
		timerImage:		"timer.gif",
		debug:			false,
		hoverSelector:	".kinectselectable",
		onError: function (msg){
			alert(msg);
		},
		onFrame: function (ev){},
		onGesture: function (ev){},
		onActivePlayerChanged: function (ev){},
		onKinectHover: function (ev){},
		onKinectClick: function (ev){}
	}; 
  
	var options = $.extend({}, defaults, options); 
	
	var connected = false;
	var controlPointer = $(this);
	
	if ("WebSocket" in window) {
		var ws;
		
		try {
			ws = new WebSocket(options.wsServer);
		} catch (err) {
			options.onError.call(this, "Error opening websocket: " + err);
		}
		
		ws.onopen = function () {
			var jsonObj = [];
			jsonObj.push({
				CaptureFrames: options.captureFrames,
				ScreenWidth: options.boxWidth,
				ScreenHeight: options.boxHeight,
				AccelerationX: parseFloat(options.accelerationX),
				AccelerationY: parseFloat(options.accelerationY),
				OffsetX: parseFloat(options.offsetX),
				OffsetY: parseFloat(options.offsetY),
				OnePlayerOnly: options.onePlayeronly,
				ElevationAngle: options.elevationAngle
			});
			
			ws.send(JSON.stringify(jsonObj[0]));
			
			var startX = (options.boxWidth / 2) - (controlPointer.width() / 2);
			var startY = (options.boxHeight / 2) - (controlPointer.height() / 2);
		
			$(controlPointer).css({"top": startY, "left": startX });
		
			if(options.debug == true){
				controlPointer.draggable();
			}
			
			connected = true;
			
			setInterval(function() { KinectCollisionDetection(); }, options.cdi);
		};

		ws.onmessage = function (evt) {
			var ev = JSON.parse(evt.data);
			
			if (ev.EventName == "OnFrame"){
				options.onFrame.call(this, ev.Args);
				KinectFrameHandler(ev.Args);
			}
			
			if (ev.EventName == "OnGesture"){
				options.onGesture.call(this, ev.Args);
			}
			
			if (ev.EventName == "OnActivePlayerChanged"){
				options.onActivePlayerChanged.call(this, ev.Args);
			}
		};

		ws.onclose = function () {
			if(connected){
				options.onError.call(this, "The connection has been dropped...");
				connected = false;
			}else{
				options.onError.call(this, "Cannot connect to WebSocket Server...");
			}
		};
		
	}else{
		options.onError.call(this, "Your Browser doesn't support web sockets !");
	}
	
    return this.each(function() {
				
	});
	
	function KinectCollisionDetection(){
		$(options.hoverSelector).each(function (i, domEle) {
			if(controlPointer.hitTestObject(jQuery(this))){
				//Hovered
				
				if(jQuery(this).attr('kinecthovered') == 'false' || jQuery(this).attr('kinecthovered') == undefined){
				
					jQuery(this).attr('kinecthovered', 'true');
			
					var jsonObj = [];
					jsonObj.push({
						hoverobject: jQuery(this),
						hovermode: "in",
						hoverid: jQuery(this).attr('id'),
						kinectpointer: controlPointer
					});
				
					options.onKinectHover.call(this, jsonObj[0]);
					KinectHoverHandler(jsonObj[0]);
				}
				
			}else{
				//Not hovered
				
				if(jQuery(this).attr('kinecthovered') == 'true'){
				
					jQuery(this).attr('kinecthovered', 'false');
							
					var jsonObj = [];
					jsonObj.push({
						hoverobject: jQuery(this),
						hovermode: "out",
						hoverid: jQuery(this).attr('id'),
						kinectpointer: controlPointer
					});
				
					options.onKinectHover.call(this, jsonObj[0]);
					KinectHoverHandler(jsonObj[0]);
				}
			}		
		});
	}
	
	function KinectHoverHandler(e){
		var en = e.kinectpointer.attr('clickenabled');
		
		if(en == 'true' || en == undefined){
			if(e.hovermode == "in"){
				currentHoverTimeout = setTimeout(function() { KinectTimedClick(e); }, options.hoverTime);
				e.hoverobject.attr('timerid', currentHoverTimeout);
				e.kinectpointer.empty();
				e.kinectpointer.append('<img src="' + options.timerImage + '?' + new Date().getTime() + '" />');
			}else{
				var tempTimeout;
				tempTimeout = currentHoverTimeout;
				
				currentHoverTimeout = e.hoverobject.attr('timerid');
				clearTimeout(currentHoverTimeout);
				
				if(tempTimeout == currentHoverTimeout){
					e.kinectpointer.empty();
				}
			}
		}
	}
	
	function KinectFrameHandler(e){
		var joint;
		joint = e.Joints.HandRight;
		
		var newX = joint.ScreenX - (controlPointer.width() / 2);
		var newY = joint.ScreenY - (controlPointer.height() / 2);
		
 		controlPointer.css({ "top": newY, "left": newX });
	}
	
	function KinectTimedClick(e){
		var jsonObj = [];
		jsonObj.push({
			hoverobject: e.hoverobject,
			hoverid: e.hoverid,
			kinectpointer: e.kinectpointer
		});
		
		e.kinectpointer.empty();
				
		options.onKinectClick.call(this, jsonObj[0]);
	}

	function disableKinectPointer(pointer, timeout){
		pointer.attr('clickenabled', false);
		setTimeout(function() { pointer.attr('clickenabled', true); }, timeout);
	}

  };
})( jQuery );

jQuery.fn.hitTestObject=function(target){
	var src=jQuery(this);
	var x1=src.offset().left,y1=src.offset().top,w=src.outerWidth(),h=src.outerHeight();
	var xp1=target.offset().left,yp1=target.offset().top,wp=target.outerWidth(),hp=target.outerHeight();
	var x2=x1+w,y2=y1+h,xp2=xp1+wp,yp2=yp1+hp;
	if(xp1>=x1 && xp1<=x2 ){
		if(yp1>=y1 && yp1<=y2){	return true; }else if(y1>=yp1 && y1<=yp2){ return true;	}
	}else if(x1>=xp1 && x1<=xp2){
		if(yp1>=y1 && yp1<=y2){	return true; }else if(y1>=yp1 && y1<=yp2){ return true;	}
	}
	return false;
};

function pageWidth() {return window.innerWidth != null? window.innerWidth: document.body != null? document.body.clientWidth:null;}
function pageHeight() {return window.innerHeight != null? window.innerHeight: document.body != null? document.body.clientHeight:null;} 